﻿using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Jinjia.Approve.Entity.Entity.JJFlow;
using Jinjia.Approve.IRepository.JJFlow;
using Jinjia.Core.UnitOfWork.UnitOfWorkComponent;
using SqlSugar;

namespace Jinjia.Approve.Repository.JJFlow
{
    public class FlowNodeReferenceRepository : IFlowNodeReferenceRepository
    {
        private readonly ISqlSugarClient _db;

        public FlowNodeReferenceRepository(IUnitOfWork unitOfWork)
        {
            _db = unitOfWork.GetDbClient();
        }

        public async Task<int> Save(jj_node_reference data)
        {
            if (data.id <= 0) //新增
            {
                var id = await _db.Insertable(data).ExecuteReturnIdentityAsync();
                return id;
            }
            else
            {
                await _db.Updateable(data)
                    .Where(x => x.id == data.id)
                    .ExecuteCommandAsync();
                return data.id;
            }
        }

        public async Task Save(List<jj_node_reference> data)
        {
            var insertData = data.Where(x => x.id <= 0).ToList();

            if (insertData.Any())
            {
                await _db.Insertable(insertData).ExecuteCommandAsync();
            }

            var updateData = data.Where(x => x.id > 0).ToList();

            if (updateData.Any())
            {
                await _db.Updateable(insertData).ExecuteCommandAsync();
            }
        }

        public async Task<List<jj_node_reference>> GetReferences(int flow_instance_id)
        {
            return await _db.Queryable<jj_node_reference>()
                .Where(x => x.flow_instance_id == flow_instance_id)
                .OrderBy(" sequence asc ")
                .ToListAsync();
        }

        public async Task<jj_node_reference> GetNodeByInstanceIdAndNodeId(int instance_id, int node_id)
        {
            return await _db.Queryable<jj_node_reference>().Where(a => a.flow_instance_id == instance_id && a.node_id == node_id).FirstAsync();
        }
    }
}